<?php


namespace app\admin\controller;
use app\common\model\mysql\AdminUser as AdminUserModel;
use think\App;
use think\Exception;
use think\facade\View;
use app\BaseController;
use app\common\model\mysql\AdminAuth;
use app\common\model\mysql\AdminTaxon;
use think\auth\Auth as Auth_Rules;
class Auth extends BaseController
{
    //需要多次调用的模型放到成员属性中
    private $auth;
    private $model;
    private $jurisdiction;

    public function __construct()
    {
        $this->model = new AdminUserModel;
        $this->jurisdiction = new AdminAuth;
        $this->auth = Auth_Rules::instance();
    }

    //添加管理员
    public function AddAdmin()
    {
        if ($this->auth->check('Auth/allocation', session(config("session.session_admin"))['id'])){
            return view();
        }
    }

    //把信息进数据库
    public function AddManage()
    {
        if ($this->auth->check('Auth/allocation', session(config("session.session_admin"))['id'])) {
            //是否为post请求访问
            if (!request()->isPost()) {
                return show(config("status.error"), '请求方式错误');
            }

            //接收post提交的数据
            $mes = request()->param('mes');
            $data = [
                'newpass' => $mes['newpass'],
                'repass' => $mes['repass'],
                'username' => $mes['username']
            ];

            //验证器再次校验输入格式是否正确
            $validate = new \app\admin\validate\AddAuth();
            if (!$validate->check($data)) {
                return show(config("status.error"), $validate->getError());
            }

            //数据没问题后调用business层
            try {
                $result = \app\admin\business\AddAuth::authority($data);
            } catch (\Exception $e) {
                return show(config("status.error"), $e->getMessage());
            }

            //判断business层的数据
            if ($result) {
                return show(config("status.success"));
            } else {
                return show(config("status.error"));
            }

            return true;
        }
    }

    //添加管理员页
    public function allot()
    {
        if ($this->auth->check('Auth/allocation', session(config("session.session_admin"))['id'])) {
            //page 页数
            $mesage = request()->param(['page']);

            //把页数传过去分页
            $data = $this->model->StayActivate($mesage);

            //渲染页面加载数据
            View::assign('message', $data);

            return view();
        }
    }

    //角色管理页面
    public function admin_role()
    {
        if ($this->auth->check('Auth/admin_role', session(config("session.session_admin"))['id'])) {
            return View::fetch('Auth/admin-role');
        }
    }

    //为未开启的管理员激活
    public function start()
    {
        if ($this->auth->check('Auth/allocation', session(config("session.session_admin"))['id'])) {
            //是否为post请求访问
            if (!request()->isPost()) {
                return show(config("status.error"), '请求方式错误');
            }

            //接收post传来的id
            $id = request()->param('id');

            try {

                //修改该id状态 status
                $demo = $this->model->initiated($id);

                if (empty($demo)) {
                    return show(config("status.error"), '未知异常!');
                }
            } catch (\Exception $e) {
                throw new Exception($e->getMessage());
            }
            $username = $this->model->find($id);
            $this->jurisdiction->addSave($id,$username->username);
            return show(config("status.success"), '开启成功!');
        }
    }

    //删除未激活的管理员
    public function remove()
    {
        if ($this->auth->check('Auth/allocation', session(config("session.session_admin"))['id'])) {
            //是否为post请求访问
            if (!request()->isPost()) {
                return show(config("status.error"), '请求方式错误');
            }

            //进行删除
            try {
                //接收post传来的id
                $id = request()->param('id');

                //根据id来删除
                $demo = $this->model->RemoveAdminUser($id);

                if (empty($demo)) {
                    return show(config("status.error"), '未知异常!');
                }
            } catch (\Exception $e) {
                throw new Exception($e->getMessage());
            }

            return show(config("status.success"), '删除成功!');
        }
    }

    //删除多条未激活的管理员
    public function  deletemultiple()
    {
        if ($this->auth->check('Auth/allocation', session(config("session.session_admin"))['id'])) {
            //是否为post请求访问
            if (!request()->isPost()) {
                return show(config("status.error"), '请求方式错误');
            }

            try {
                //接收post传来的id
                $id = request()->param('id');

                //把数据发送过去
                $data = $this->model->RemoveAdminUser($id);

                if (empty($data)) {
                    return show(config("status.error"), '未知异常');
                }
            } catch (\Exception $e) {
                throw new Exception($e->getMessage());
            }

            return show(config("status.success"), '删除成功!');

        }

    }

    //角色管理页查询
    public function getGroup()
    {
        if ($this->auth->check('Auth/admin_role', session(config("session.session_admin"))['id'])) {
            //默认查10条
            $rows = input('limit') ?? 10;

            //默认从零开始，接收传来的page页数
            $page = input('page') ?? 1;
            $page -= 1;
            $offset = ($page) * $rows;

            //返回数据格式
            $result['code'] = 0;
            $result['msg'] = '';
            $result['count'] = $this->jurisdiction->where('username', 'like', '%' . input('username') . '%')->count();
            $result['data'] = $this->jurisdiction->where('username', 'like', '%' . input('username') . '%')->limit($offset, $rows)->select();
            return json($result);
        }
    }

    //树型结构图
    public function getUserRules()
    {
        if ($this->auth->check('Auth/admin_role', session(config("session.session_admin"))['id'])) {
            //查询该用户权限组
            $id = request()->param('id');
            $userRules = $this->jurisdiction->where('id', $id)->field('username,rules')->select()->toArray();
            $rules = explode(',', $userRules[0]['rules']);

            //获取根节点
            $result = AdminTaxon::where('id', 1)->field('title,id')->select()->toArray();

            //获取一级节点
            $children = AdminTaxon::where('pid', $result[0]['id'])->field('title,id')->order('navid')->select()->toArray();

            //获取二级节点
            $y = 0;

            foreach ($children as $value) {
                $children1 = AdminTaxon::where('pid', $value['id'])->field('title,id')->order('navid')->select()->toArray();
                if (empty($children1)) {
                    $children[$y]['children'] = array();  //二节节点不存在时将children设置为空数组
                    if (in_array($value['id'], $rules)) {
                        $children[$y]['checked'] = true;  //一节节点为末节点且有权限时设置选择状态
                    }
                } else {
                    //二节节点存在时设置为展开状态
                    $children[$y]['spread'] = true;
                    $i = 0;
                    //向二级节点数组增加checked状态并设置children为空
                    foreach ($children1 as $ch) {
                        if (in_array($ch['id'], $rules)) {
                            $children1[$i]['checked'] = true;
                        }
                        $children1[$i]['children'] = array();
                        ++$i;
                    }
                    $children[$y]['children'] = $children1;
                }
                ++$y;
            }

            //设置根节点为展开状态，并添加children
            $result[0]['spread'] = true;
            $result[0]['children'] = $children;
            return json($result);
        }
    }

    //修改管理员权限组 树型图
    public function updateGroup()
    {
        if ($this->auth->check('Auth/admin_role', session(config("session.session_admin"))['id'])) {
            //用户id
            $id = request()->param('id');

            //rules
            $field = request()->param('field');

            //rules内容
            $value = request()->param('value');

            return $this->jurisdiction->updateGroup($id, $field, $value);
        }
    }

    //删除管理员权限组
    public function delGroup()
    {
        if ($this->auth->check('Auth/admin_role', session(config("session.session_admin"))['id'])) {
            $id = request()->param('id');
            try{
                $uid = $this->jurisdiction->find($id);

                $admin_user = $this->model->RemoveAdminUser($uid->uid);
                if(empty($admin_user)){
                    return show(config("status.error"), '未知异常');
                }
            }catch (\Exception $e){
                throw new Exception($e->getMessage());
            }
            return json($this->jurisdiction->delGroup($id));
        }
    }
}